#include "qstring.h"
#include "iostream"
#include "qbytearray.h"
#include "qfile.h"
#include "qdir.h"
#include "QByteRef"
#include "qdebug.h"
#include "QCoreApplication"
#include "Core/PasswdTool/passwdctrl.h"



QString PasswdCtrl::m_dir_path = QString();
QString PasswdCtrl::m_file_full_path = QString();

void PasswdCtrl::WritePasswd(QString pw)
{
     QByteArray arr = pw.toUtf8();
     arr = arr.toBase64(QByteArray::Base64Encoding);

     auto dir_path = PasswdCtrl::GetPwDir();
     QDir dir(dir_path);
     if(!dir.exists())
     {
        dir.mkdir(dir_path);
     }

     QFile file(PasswdCtrl::GetPwFullPath());
     file.open(QFile::WriteOnly);
     file.write(arr);
     file.close();

     qDebug()<<PasswdCtrl::GetPwFullPath();
}

QString PasswdCtrl::ReadPasswd()
{
    QFile file(PasswdCtrl::GetPwFullPath());
    if(!file.exists())
    {
        QString str = QString();
        return str;
    }

    file.open(QFile::ReadOnly);
    QByteArray arr = file.readAll();
    file.close();
    arr = arr.fromBase64(arr,QByteArray::Base64Encoding);
    QString pw = QString(arr);

    return pw;
}

QString PasswdCtrl::GetPwDir()
{
    if(PasswdCtrl::m_dir_path.isEmpty())
    {
        PasswdCtrl::m_dir_path = QString("%1/pw").arg(QCoreApplication::applicationDirPath());
    }
    return PasswdCtrl::m_dir_path;
}

QString PasswdCtrl::GetPwFullPath()
{
    if(PasswdCtrl::m_file_full_path.isEmpty())
    {
        PasswdCtrl::m_file_full_path = QString("%1/pw.pw").arg(PasswdCtrl::GetPwDir());
    }
    return PasswdCtrl::m_file_full_path;
}

